<template>
  <div class="app-container">
    <el-card v-show="showSearch" class="mb10" shadow="hover">
      <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="120px" size="small">
        <el-form-item label="优惠券类型" prop="params.couponType">
          <el-select v-model="queryParams.params.couponType" placeholder="请输入优惠券类型">
            <el-option
              v-for="dict in dict.type.coupon_type"
              :key="dict.dictCode"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="ml10">
          <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="hover">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponRecord:remove']"
            :disabled="multiple"
            icon="el-icon-delete"
            plain
            size="mini"
            type="danger"
            @click="handleDelete"
          >回收
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponRecord:export']"
            icon="el-icon-download"
            plain
            size="mini"
            type="warning"
            @click="handleExport"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['market:couponRecord:add']"
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleAdd"
          >优惠券发放
          </el-button>
        </el-col>
        <right-toolbar :columns="columns" :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="couponRecordList" border @sort-change="handleSortChange"
                @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column v-if="columns[0].visible" align="center" label="券名称" prop="couponName"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[1].visible" align="center" label="券模板ID" prop="templateId"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[2].visible" align="center" label="优惠券类型" prop="couponType"
                         show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="dict.type.coupon_type" :value="scope.row.couponType"/>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" align="center" label="会员ID" prop="memberId" show-overflow-tooltip/>
        <el-table-column v-if="columns[4].visible" align="center" label="开始时间" prop="startTime"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" align="center" label="结束时间" prop="endTime" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" align="center" label="发送时间" prop="sendTime"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.sendTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" align="center" label="发券业务编码" prop="sendCode"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[8].visible" align="center" label="使用时间" prop="useTime" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.useTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[9].visible" align="center" label="销券业务编码" prop="useCode"
                         show-overflow-tooltip/>
        <el-table-column v-if="columns[10].visible" align="center" label="创建时间" prop="createDate"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[11].visible" align="center" label="编辑时间" prop="modifiedDate"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.modifiedDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[12].visible" align="center" label="备注信息" prop="remark"
                         show-overflow-tooltip/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="回收" placement="top">
              <el-button
                v-hasPermi="['market:couponRecord:remove']"
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改优惠券记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="券模板" prop="templateId">
          <el-select v-model="form.templateId" filterable placeholder="请选择优惠券">
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.couponName"
              :value="item.id">
              <span style="float: left">{{ item.couponName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.purpose }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员ID" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入会员ID"/>
        </el-form-item>
        <el-form-item label="发放数量" prop="number">
          <el-input
            v-model="form.number"
            class="filter-item"
            clearable
            placeholder="发放数量"
            type="number"
          />
        </el-form-item>
        <el-form-item label="券使用时间：" prop="startTime">
          <el-date-picker
            v-model="dateTime"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            style="width: 100%"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="dateChangeHandler"
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注信息"
                    type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addCouponRecord, getCouponRecord, listCouponRecord, updateCouponRecord} from "@/api/market/couponRecord";
import {formatDateTime, nowCnFormatDateTime} from "@/utils/date";
import {getTemplate} from "@/api/market/couponTemplate";

export default {
  name: "CouponRecord",
  dicts: ['coupon_type'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      dateTime: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券记录表格数据
      couponRecordList: [],
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sortName: 'id',
        sortOrder: 'desc',
        params: {
          templateId: undefined,
          couponType: undefined,
          memberId: undefined,
          startTime: undefined,
          endTime: undefined,
          sendTime: undefined,
          sendCode: undefined,
          useTime: undefined,
          useCode: undefined
        }
      },
      // 列信息
      columns: [
        {key: 0, label: `券名称`, visible: true},
        {key: 1, label: `券模板ID`, visible: true},
        {key: 2, label: `优惠券类型`, visible: true},
        {key: 3, label: `会员ID`, visible: true},
        {key: 4, label: `开始时间`, visible: true},
        {key: 5, label: `结束时间`, visible: true},
        {key: 6, label: `发送时间`, visible: true},
        {key: 7, label: `发券业务编码`, visible: false},
        {key: 8, label: `使用时间`, visible: false},
        {key: 9, label: `销券业务编码`, visible: false},
        {key: 10, label: `创建时间`, visible: false},
        {key: 11, label: `编辑时间`, visible: false},
        {key: 12, label: `备注信息`, visible: true},
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateId: [
          {
            required: true, message: "券模板ID不能为空", trigger: "blur"
          }
        ],
        memberId: [
          {
            required: true, message: "会员ID不能为空", trigger: "blur"
          }
        ],
        startTime: [
          {
            required: true, message: "开始时间不能为空", trigger: "blur"
          }
        ],
        number: [{
          required: true, message: "发放数量不能为空", trigger: "blur"
        }]
      }
    };
  },
  created() {
    this.getList();
    // 获取优惠券数据
    getTemplate().then(res => {
      this.templateList = res.data
    })
  },
  methods: {
    formatDateTime,
    /** 查询优惠券记录列表 */
    getList() {
      this.loading = true;
      listCouponRecord(this.queryParams).then(response => {
        this.couponRecordList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        templateId: undefined,
        couponType: undefined,
        memberId: undefined,
        startTime: undefined,
        endTime: undefined,
        sendTime: undefined,
        sendCode: undefined,
        useTime: undefined,
        useCode: undefined,
        number: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCouponRecord(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateCouponRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addCouponRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除优惠券记录编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCouponRecord(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/couponRecord/export', {
        ...this.queryParams
      }, `couponRecord_${nowCnFormatDateTime()}.xlsx`)
    },
    dateChangeHandler(value) {
      if (value) {
        this.form.startTime = value[0]
        this.form.endTime = value[1]
      }
    }
  }
}

</script>

<style>
.el-form .el-select {
  width: 100%;
}
</style>
